package cn.tsmchina.one.controller.order;



import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.tsmchina.one.domain.order.Order;
import cn.tsmchina.one.domain.user.User;
import cn.tsmchina.one.service.order.OrderService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.service.user.UserService;
import cn.tsmchina.one.util.AESUtil;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.JsonUtil;
import cn.tsmchina.one.util.LoginUtil;
import cn.tsmchina.one.util.PartnerConfig;
import cn.tsmchina.one.util.TradeUtil;
import cn.tsmchina.one.util.alipay.security.RSASignature;
import cn.tsmchina.one.util.alipay.util.ParameterUtil;


@RequestMapping("/pay")
@Controller
public class PayController
{

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private CustomerService customerService;
	@SuppressWarnings({ "unchecked" })
	@RequestMapping("/trade")
	public void trade(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		try
		{
			String value = request.getParameter("p");
			System.out.println(value);
			String replace = value.replace(" ", "+");
			System.out.println(replace);
			String decrypt = AESUtil.decrypt(replace);
			System.err.println(decrypt);
			if(decrypt == null)
			{
				response.getWriter().write("非法请求!");
				return;
			}
			Map<String, Object> data = JsonUtil.parseObject(Map.class,decrypt);
			String name = (String) data.get("name");
			double price = (double) data.get("price");
			long orderId = (long) data.get("orderId");
			TradeUtil.trade(request, response, name, String.valueOf(price), String.valueOf(orderId));
		} catch (Exception e)
		{
			response.getWriter().write(e.getMessage());
			e.printStackTrace();
		}
	}

	@RequestMapping("/repay")
	public void repay(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		try
		{

			String name = "红高粱菜品";
			String price = request.getParameter("price");
			String orderId = request.getParameter("orderId");
			TradeUtil.trade(request, response, name, String.valueOf(price), String.valueOf(orderId));
		} catch (Exception e)
		{
			response.getWriter().write(e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 接收支付报通知
	 * @author YUE
	 * @date 2013-6-28 下午8:02:20
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/notify")
	public void notify(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String sign = request.getParameter("sign");
		String data = request.getParameter("notify_data");
		String service = request.getParameter("service");
		String v = request.getParameter("v");
		String sec_id = request.getParameter("sec_id");
		
		boolean check = false;
		try
		{
			 data = RSASignature.decrypt(data, PartnerConfig.RSA_PRIVATE);
			 String notify_data = "service=" + service + "&v=" + v + "&sec_id=" + sec_id+ "&notify_data=" +data;
			 System.out.println("------"+notify_data);
			check = RSASignature.doCheck(notify_data, sign,PartnerConfig.RSA_ALIPAY_PUBLIC, "");
			 if (check)
			{
				System.out.println(":data-----------"+data);
				Long orderId = Long.parseLong(ParameterUtil.getParameterAsXml(data, "out_trade_no"));
				System.out.println("order_Id:---------"+orderId);
				orderService.updatePayStatus(orderId);
				
				long cid = LoginUtil.getCustomerId(request, customerService);
				Order order = orderService.getUserOrders(orderId, cid).get(0);
				User user = (User) userService.getUser(order.getUserId());
				int inCredits = (int)Math.ceil(order.getTotalPrice())*C.CASH_SCORE_EXCHANGE_RATIO;////TODO 使获取积分比例可配置
				int outCredits = order.getCredits();
				userService.updateUserCredits(user.getId(), inCredits-outCredits);
			}
		}catch (Exception e) 
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
			check = false;
		}
		PrintWriter out = response.getWriter();
		 if(check)
			 out.print("success");
		 else
			 out.print("fail");
		out.close();
	}

	/**
	 * 回调
	 * @author YUE
	 * @date 2013-6-28 下午8:03:17
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/callback")
	public String callback(HttpServletRequest request,HttpServletResponse response,Model model)
	{
		String result = request.getParameter("result");
		if(result.equals("success"))
		{
			return "m/paySuccess";
		}
		else
		{
			return "m/payFailure";
		}
	}

	@RequestMapping("/merchant")
	public Object merchant(HttpServletResponse response)
	{
		return "m/payFailure";
	}
}
